<?php

namespace App\Http\Controllers\Guard\Article;

use App\Http\Controllers\Common\GuardController;
use App\Models\Article\ArticleClassify;
use App\Models\Article\ArticleInfo;
use App\Models\Article\ArticleOrder;
use App\Models\Constant\Constant;
use App\Models\Constant\FileConstant;
use App\Models\Setting\SysSetting;
use App\Models\User\MemberOrder;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use PhpOffice\PhpWord\IOFactory;

class ArticleInfoController extends GuardController {

    public function summary(Request $request) {
        $today = date('Y-m-d');

        $todayMewUser =  User::whereDate('created_at',$today)->count();//今日新增用户
        $todayMewMember =  MemberOrder::whereDate('created_at',$today)->where('is_finished',1)
            ->where('is_auto',1)
            ->count();//今日新增会员

        $todayMemberFee = MemberOrder::whereDate('created_at',$today)
            ->where('is_auto',1)
            ->where('is_finished',1)->sum('fee');//今日会员收益
        $todayArticleFee = ArticleOrder::whereDate('created_at',$today)
            ->where('is_finished',1)->sum('fee');//今日文档收益

        $todayFee = round($todayMemberFee+$todayArticleFee,1);//今日总收益

        $memberFee = MemberOrder::where('created_at','>=',Constant::SUB_TIME)
            ->where('is_finished',1)
            ->where('is_auto',1)
            ->sum('fee');//全年总会员收益

        $articleFee = ArticleOrder::where('created_at','>=',Constant::SUB_TIME)
            ->where('is_finished',1)
            ->where('is_auto',1)
            ->sum('fee');//全年总文档收益

        $countFee = round($memberFee+$articleFee,1);//全年总收入

        $countUser = User::count();//总用户
        $memberUsers = User::where('is_member',1)->get(['id','type']);
        $countMember = $memberUsers->count();//总会员
        $firstUsers = $memberUsers->where('type','first')->count();
        $monthUsers = $memberUsers->where('type','month')->count();
        $quarterUsers = $memberUsers->where('type','quarter')->count();
        $yearUsers = $memberUsers->where('type','year')->count();

        $buyMember = MemberOrder::whereDate('created_at',date('Y-m-d'))->where('is_finished',1)
            ->where('is_auto',1)
            ->orderByDesc('id')
            ->with('getUser:id,avatar,nick_name')->get();
        $buyExCodeMember = MemberOrder::whereDate('created_at',date('Y-m-d'))->where('is_finished',1)
            ->where('is_auto',3)
            ->orderByDesc('id')
            ->with('getUser:id,avatar,nick_name')->get();
        $buyArticle = ArticleOrder::whereDate('created_at',date('Y-m-d'))->where('is_finished',1)
            ->orderByDesc('id')
            ->with(['getUser:id,avatar,nick_name','getArticle:id,title'])->get();
        foreach ($buyMember as $item) { $item->type = Constant::MAP_MEMBER[$item->type]??'未知';}


        $exCodeTodayMemberFee = MemberOrder::whereDate('created_at',$today)
            ->where('is_auto',3)->where('is_finished',1)->sum('fee');//今日兑换码收益

        $exCodeMemberFee = MemberOrder::where('created_at','>=',Constant::SUB_TIME)->where('is_auto',3)->where('is_finished',1)->sum('fee');//全年总会员收益

        $info = compact('exCodeMemberFee','exCodeTodayMemberFee','buyMember','buyExCodeMember','buyArticle','todayMewMember','todayArticleFee','todayMemberFee','todayFee','todayMewUser','countFee','countMember','countUser','firstUsers','monthUsers','quarterUsers','yearUsers');

        return responseSuccess($info);
    }

    public function pptLst(Request $request) {
        $classifies = ArticleClassify::pluck('name','id')->toArray();
        try{
            $page = $request->input('page',1);
            $pageSize = $request->input('pageSize',Constant::PAGE_SIZE);
            $ids = $request->input('id',0);
            $title = $request->input('title','');
            $classifyId = $request->input('classifyId','all');
            $conditions = compact('classifyId','title','ids');
//            $conditions['orderBy']['col'] = 'sort';
//            $conditions['orderBy']['sort'] = 'desc';
            $sql = 'CHAR_LENGTH(img_urls)<=70';
            $records = (new ArticleInfo)->getLst($conditions)
                ->where('type','pptx')->whereRaw($sql)
                ->paginate($pageSize,['*'],'page',$page);
            foreach ($records as $record) {
                $record->description = Str::limit($record->description,20);
                $record->content = Str::limit($record->content,20);
                $record->is_sensitive_name = $record->is_sensitive==1?'是':'否';
//                $record->up_down_name = $record->up_down==1?'是':'否';
//                $record->is_top_name = $record->is_top==1?'是':'否';
                $record->classify_name = $classifies[$record->classify_id]??'未知';
            }
            return responseSuccess($records->items(),$records->total());
        }catch(\Exception $e){
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }
    }
    public function lst(Request $request) {
        $classifies = ArticleClassify::pluck('name','id')->toArray();
        try{
            $page = $request->input('page',1);
            $pageSize = $request->input('pageSize',Constant::PAGE_SIZE);
            $ids = $request->input('id',0);
            $title = $request->input('title','');
            $classifyId = $request->input('classifyId','all');
            $conditions = compact('classifyId','title','ids');
//            $conditions['orderBy']['col'] = 'sort';
//            $conditions['orderBy']['sort'] = 'desc';

            $records = (new ArticleInfo)->getLst($conditions)->paginate($pageSize,['*'],'page',$page);
            foreach ($records as $record) {
                $record->description = Str::limit($record->description,20);
                $record->content = Str::limit($record->content,20);
                $record->is_sensitive_name = $record->is_sensitive==1?'是':'否';
//                $record->up_down_name = $record->up_down==1?'是':'否';
//                $record->is_top_name = $record->is_top==1?'是':'否';
                $record->classify_name = $classifies[$record->classify_id]??'未知';
            }
            return responseSuccess($records->items(),$records->total());
        }catch(\Exception $e){
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }
    }

    public function add(Request $request) {

        try{
            $id = $request->input('id',0);
            $info = $request->except('id');

            //编辑
            /*if($id>0){

                //如果img_urls只有一张图，说明是封面
                $article = ArticleInfo::query()->find($id);
                if(count($info['img_urls'])<=0){
                    //nothing
                }
                else if(count($info['img_urls'])==1){
                    $article->img_urls =  Arr::first($info['img_urls']).','.$article->img_urls;
                }else{
                    $article->img_urls = implode(',', $info['img_urls']);
                }

                $article->save();
                return responseSuccess();
            }*/

            if(isset($info['classify_id']) && is_array($info['classify_id'])){
                $info['classify_id'] = Arr::last($info['classify_id']);
            }

            if(Str::contains($info['title'], '八项') || Str::contains($info['title'], '民主生活会'))
                $info['is_sensitive'] = 1;


            if(count($info['img_urls'])<=0){
                //如果没有上传封面
                unset($info['img_urls']);
            }
            else if(count($info['img_urls'])==1 && $id>0){
                //如果只上传了一张图，并且是编辑模式，说明是修改封面，就把它放在最前边
                $article = ArticleInfo::query()->find($id);
                $info['img_urls'] =  Arr::first($info['img_urls']).','.$article->img_urls??'';
            }else{
                //如果上传了多张图，则正常保存
                $info['img_urls'] = implode(',', $info['img_urls']);
            }
            //$info['img_urls'] = count($info['img_urls'])<=0?null:implode(',', $info['img_urls']);
            ArticleInfo::updateOrCreate(compact('id'),$info);
            return responseSuccess();
        }catch(\Exception $e){
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($tip);
            return responseFail($tip);
        }
    }

    public function addBatch(Request $request) {
        $articles = $request->input('articles');
        $is_sensitive = $request->input('is_sensitive',2);
        $error = [];
        foreach ($articles as &$article) {
            try{

//                if(in_array($article['type'], [FileConstant::FILE_TYPE_DOC,FileConstant::FILE_TYPE_DOCX])){
//                    $article['price'] = 3.5;
//                }
                //if(isset($article['type']))unset($article['type']);
                $article['see_num'] = 0;
                $article['download_num'] = 0;
                $article['created_at'] = date('Y-m-d H:i:s');
                $article['updated_at'] = date('Y-m-d H:i:s');
                $article['is_sensitive'] = $is_sensitive;

                //如果文档中名字含有“八项”，则一定设置成敏感
                if(Str::contains($article['title'], '八项') || Str::contains($article['title'], '民主生活会'))
                    $article['is_sensitive'] = 1;
                if(isset($article['summary']))unset($article['summary']);
                ArticleInfo::create($article);
            }catch(\Exception $e){
                $error[] = $article['title'].':'.$e->getMessage();
            }
        }
        if(count($error)>0){
            return responseSuccess($error,0,100000,[],false);
        }
        return responseSuccess();
    }

    public function uploadFile(Request $request) {

        $file = $request->file('file');
        $count = $request->input('count',0);
        if(empty($file) || !$file->isValid()){
            return responseFail('文件无效！');
        }
        $size =  $file->getSize();
        $ext = $file->getClientOriginalExtension();
        $originName = $file->getClientOriginalName();
        $module = $request->input('module','article');

        /*if(!in_array($ext, array_keys(FileConstant::MAP_FILE_TYPE)))
            return responseFail('文件格式错误！');*/

        //检查目录
        $middlePath = "/$module/".date('Y')."/".date('m').'/'.date('d');
        $absDir = Storage::disk('upload')->path($middlePath);
        if(!is_dir($absDir)){mkdir($absDir,0777,true);}

        //重命名
        $fileName = time().uniqid().".$ext";
        $filePath = $file->storeAs($middlePath,$fileName,'upload');
        $filePath = '/storage/upload/'.$filePath;
        $url = asset($filePath);
        $path = public_path($filePath);
        try{
            $body='';
            $summary='';
            if($ext==FileConstant::FILE_TYPE_DOCX){
                $body = $result = $this->readWordToHtml($path);
                $ps = explode('<p', $body);
                $summary = '';
                foreach ($ps as &$p) {
                    if(!empty($p))
                        $p="<p".$p;
                    $summary.=$p;

                    $summaryMax = SysSetting::where('key','summaryMax')->first()->val??2000;

                    if(strlen($summary)>=$summaryMax){
                        break;
                    }
                }
            }
            return responseSuccess(compact('filePath','count','size','url','originName','body','summary','ext'));
        }catch(\Exception $e){
            $tip = $originName.':'.$e->getMessage();
            Log::error($tip);
            return responseFail($tip);
        }catch (\Error $e){
            $tip = $originName.':'.$e->getMessage();
            Log::error($tip);
            return responseFail($tip);
        }
    }

    public function readWordToHtml($source) {
        $phpWord = IOFactory::load($source);
        $html = '';
        foreach ($phpWord->getSections() as $section) {
            foreach ($section->getElements() as $ele1) {
                $paragraphStyle= null;
                if(method_exists($ele1, 'getParagraphStyle')){
                    $paragraphStyle = $ele1->getParagraphStyle();
                }
                if ($paragraphStyle) {
                    $html .= '<p style="text-align:'. $paragraphStyle->getAlignment() .';text-indent:20px;">';
                } else {
                    $html .= '<p>';
                }
                if ($ele1 instanceof \PhpOffice\PhpWord\Element\TextRun) {
                    foreach ($ele1->getElements() as $k=>$ele2) {
                        if ($ele2 instanceof \PhpOffice\PhpWord\Element\Text) {
                            $style = $ele2->getFontStyle();
                            $fontFamily = mb_convert_encoding($style->getName(), 'GBK', 'UTF-8');
                            $fontSize = $style->getSize();
                            $isBold = $style->isBold();
                            $styleString = '';
                            $fontFamily && $styleString .= "font-family:{$fontFamily};";
                            $fontSize && $styleString .= "font-size:{$fontSize}px;";
                            $isBold && $styleString .= "font-weight:bold;";
                            $html .= sprintf('<span style="%s">%s</span>',
                                $styleString,
                                mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8')
                            );
                        }
                    }
                }elseif ($ele1 instanceof \PhpOffice\PhpWord\Element\Table) {
                    $html.="<table>";
                    foreach ($ele1->getRows() as $row) {
                        $html.="<tr>";
                        foreach ($row->getCells() as $cell) {
                            $html.="<td>";
                            foreach ($cell->getElements() as $c)
                            {
                                $html.=self::getTableTextNode($c);
                            }
                            $html.="</td>";
                        }
                        $html.="</tr>";
                    }
                    $html.="</table>";
                }
                $html .= '</p>';
            }
        }
        //return $html;
        return mb_convert_encoding($html, 'UTF-8', 'GBK');
    }


    public function readWordToHtmlOrgin($source) {

        $phpWord = IOFactory::load($source);
        $html = '';
        foreach ($phpWord->getSections() as $section) {
            foreach ($section->getElements() as $ele1) {

                $paragraphStyle= null;
                if(method_exists($ele1, 'getParagraphStyle')){
                    $paragraphStyle = $ele1->getParagraphStyle();
                }

                if ($paragraphStyle) {
                    $html .= '<p style="text-align:'. $paragraphStyle->getAlignment() .';text-indent:20px;">';
                } else {
                    $html .= '<p>';
                }
                if ($ele1 instanceof \PhpOffice\PhpWord\Element\TextRun) {
                    foreach ($ele1->getElements() as $k=>$ele2) {
                        if ($ele2 instanceof \PhpOffice\PhpWord\Element\Text) {
                            //$html .= mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8');
                            $style = $ele2->getFontStyle();
                            $fontFamily = mb_convert_encoding($style->getName(), 'GBK', 'UTF-8');
                            $fontSize = $style->getSize();
                            $isBold = $style->isBold();
                            $styleString = '';
                            $fontFamily && $styleString .= "font-family:{$fontFamily};";
                            $fontSize && $styleString .= "font-size:{$fontSize}px;";
                            $isBold && $styleString .= "font-weight:bold;";
                            $html .= sprintf('<span style="%s">%s</span>',
                                $styleString,
                                mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8')
                            );
                        } elseif ($ele2 instanceof \PhpOffice\PhpWord\Element\Image) {
                            /*$imageSrc = 'images/' . md5($ele2->getSource()) . '.' . $ele2->getImageExtension();
                            $imageData = $ele2->getImageStringData(true);
                            $imageData = 'data:' . $ele2->getImageType() . ';base64,' . $imageData;
                            file_put_contents($imageSrc, base64_decode($imageData));
                            $html .= '<img src="'. $imageSrc .'" style="width:100%;height:auto">';*/
                        }
                    }
                }elseif ($ele1 instanceof \PhpOffice\PhpWord\Element\Table) {
                    $html.="<table>";
                    foreach ($ele1->getRows() as $row) {
                        $html.="<tr>";
                        foreach ($row->getCells() as $cell) {
                            $html.="<td>";
                            foreach ($cell->getElements() as $c)
                            {
                                $html.=self::getTableTextNode($c);
                            }
                            $html.="</td>";
                        }
                        $html.="</tr>";
                    }
                    $html.="</table>";
                }
                $html .= '</p>';
            }
        }
        return mb_convert_encoding($html, 'UTF-8', 'GBK');
    }

    /**
     * 获取表格节点内容
     * @param $node
     * @return string
     */
    public static function getTableNode($node)
    {
        $return = '';
        //处理行
        if ($node instanceof \PhpOffice\PhpWord\Element\Row) {
            foreach ($node->getCells() as $ele)
            {
                $return .= self::getTableNode($ele);
            }
        }
        //处理列
        else if ($node instanceof \PhpOffice\PhpWord\Element\Cell) {
            foreach ($node->getElements() as $ele)
            {
                $return .= self::getTextNode($ele);
            }
        }
        return $return;
    }

    public static function getTableTextNode($node)
    {
        $return = '';
        //处理文本
        if ($node instanceof \PhpOffice\PhpWord\Element\Text)
        {
            $txt = $node->getText();
            if(!empty($txt))
                $return .= mb_convert_encoding($txt, 'GBK', 'UTF-8');
        }
        //处理图片
        else if ($node instanceof \PhpOffice\PhpWord\Element\Image)
        {
            //$return .= self::pic2text($node);
        }
        //处理文本元素
        else if ($node instanceof \PhpOffice\PhpWord\Element\TextRun) {
            foreach ($node->getElements() as $ele) {
                $return .= self::getTableTextNode($ele);
            }
        }
        return $return;
    }

    public static function getTextNode($node)
    {
        $return = '';
        //处理文本
        if ($node instanceof \PhpOffice\PhpWord\Element\Text)
        {
            $return .=mb_convert_encoding($node->getText(), 'GBK', 'UTF-8');
        }
        //处理图片
        else if ($node instanceof \PhpOffice\PhpWord\Element\Image)
        {
            //$return .= self::pic2text($node);
        }
        //处理文本元素
        else if ($node instanceof \PhpOffice\PhpWord\Element\TextRun) {
            foreach ($node->getElements() as $ele) {
                $return .= self::getTextNode($ele);
            }
        }
        return $return;
    }

    public function change(Request $request) {

        $id = $request->input('id');

        if(is_array($id) && $request->has('is_sensitive')){
            $is_sensitive = $request->input('is_sensitive');
            ArticleInfo::query()->whereIn('id', $id)->update(['is_sensitive'=>$is_sensitive]);
            return responseSuccess();
        }

        ArticleInfo::where(compact('id'))->update($request->input());
        return responseSuccess();
    }


    public function getRecord(Request $request) {
        return $this->getRecordByIds(ArticleInfo::class, $request->input('id','')); // TODO: Change the autogenerated stub
    }

    public function del(Request $request) {

        $id = $request->input('id');
        if(is_array($id)){
            ArticleInfo::query()->whereIn('id', $id)->delete();
            return responseSuccess();
        }

        return $this->delRecords(ArticleInfo::class, $request->input('id',''));
    }

    public function uploadVideo(Request $request) {
        $fileKeys = array_keys($request->file());
        foreach ($fileKeys as $fileKey) {
            $file = $request->file($fileKey);
            $ext = $file->getClientOriginalExtension();
            $middlePath = "/article/".date('Y-m-d');
            $absDir = Storage::disk('upload')->path($middlePath);
            if(!is_dir($absDir)){mkdir($absDir,0777,true);}
            $fileName = time().uniqid().".$ext";
            $filePath = $file->storeAs($middlePath,$fileName,'upload');
            $filePath = '/storage/upload/'.$filePath;
            $info= [
                'url'=>asset($filePath),
            ];
            return response()->json([
                'data'=>$info,
                'errno'=>0
            ]);
        }
    }

    public function uploadImg(Request $request) {
        $fileKeys = array_keys($request->file());
        $info = [];
        foreach ($fileKeys as $fileKey) {
            $file = $request->file($fileKey);
            $ext = $file->getClientOriginalExtension();
            $middlePath = "/article/".date('Y-m-d');
            $absDir = Storage::disk('upload')->path($middlePath);
            if(!is_dir($absDir)){mkdir($absDir,0777,true);}
            $fileName = time().uniqid().".$ext";
            $filePath = $file->storeAs($middlePath,$fileName,'upload');
            $filePath = '/storage/upload/'.$filePath;
            $info[] = [
                'url'=>asset($filePath),
                'atl'=>'图片',
                'href'=>''
            ];

        }
        return response()->json([
            'data'=>$info,
            'errno'=>0
        ]);

    }



}
